
<template>
  <div>
    <div class="dibu2">
      <span id="marquee1">{{ message }}{{ message }}</span>
      <span id="marquee2">{{ message }}{{ message }}</span>
    </div>
  </div>
</template>

<script>
export default {
  props: ["message"],
  data() {
    return {
      marqueeVar: null,
      speed1: 0,
      speed2: 0,
    };
  },
  created() {
    setTimeout(() => {
      this.runMarquee();
    }, 2000);
    console.log('我执行了啊');
   
  },

  beforeDestroy() {
    clearInterval(this.marqueeVar);
     //       clearInterval(this.marqueeVar);
        this.marqueeVar = null;
        console.log('我销毁了熬');
  },
  methods: {
    //将移动的关键代码移出
    moveMarquee() {
      // 获取内容区宽度
      var width1 = document
        .getElementById("marquee1")
        .getBoundingClientRect().width;
      var width2 = document
        .getElementById("marquee2")
        .getBoundingClientRect().width;
      //width为第二个span标签尾部到盒子尾部的距离，500为外层盒子的宽度
      var width = width1 + width2 - 500;
      var marquee1 = document.getElementById("marquee1");
      var marquee2 = document.getElementById("marquee2");
      this.speed1 = this.speed1 - 1;
      this.speed2 -= 1;
      // 如果speed2的尾部移到盒子的尾部并且speed1的移动距离不超过文字的距离
      if (-this.speed2 >= width && -this.speed1 >= width1) {
        //让speed1重新在原位置移动
        this.speed1 = 500;
      }
      if (-this.speed2 >= width1 + width2) {
        //如果speed2的尾部移动到盒子的头部，让speed2跟在speed1之后移动
        this.speed2 = 0;
      }
      marquee1.style.transform = "translateX(" + this.speed1 + "px)";
      marquee2.style.transform = "translateX(" + this.speed2 + "px)";
    },
    runMarquee() {
      var marquee1 = document.getElementById("marquee1");
      var marquee2 = document.getElementById("marquee2");
      this.marqueeVar = setInterval(() => this.moveMarquee(), 30);
      //监听鼠标移入，清空定时器
      marquee1.addEventListener("mouseenter", () => {
        clearInterval(this.marqueeVar);
        this.marqueeVar = null;
      });
      marquee2.addEventListener("mouseenter", () => {
        clearInterval(this.marqueeVar);
        this.marqueeVar = null;
      });
      //监听鼠标移开，重启定时器
      marquee1.addEventListener("mouseleave", () => {
        this.marqueeVar = setInterval(() => this.moveMarquee(), 30);
      });
      marquee2.addEventListener("mouseleave", () => {
        this.marqueeVar = setInterval(() => this.moveMarquee(), 30);
      });
    },
  },
};
</script>

<style>
.dibu2 {
  width: 1200px;
  font-size: 0.16rem;
  overflow: hidden;
  white-space: nowrap;
  color: rgb(255, 166, 14);
}

#marquee1 {
  display: inline-block;
}

#marquee2 {
  display: inline-block;
}
</style>

